<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Groups extends CI_Controller {
    /* PAGES */

    /**
     * Constructeur de la class Groups.
     */
    public function __construct() {
        parent::__construct();

        $this->acl->setModule('groups');
    }

    /**
     * Page d'administration des groupes.
     */
    public function admin() {
        $this->acl->can('manage');

        $crud = new grocery_CRUD();

        $crud->set_table('S_INTRANET.V_GROUP_GRP')
                ->set_subject('un groupe')

                // Champs.
                ->columns('GRP_NAME', 'GRP_DESCRIPTION')
                ->fields('GRP_NAME', 'GRP_DESCRIPTION', 'USERS')
                ->required_fields('GRP_NAME')

                // Affichage.
                ->display_as('GRP_DESCRIPTION', 'Description')
                ->display_as('GRP_NAME', 'Nom')

                // Relations.
                ->set_relation_n_n('USERS', 'S_INTRANET.T_J_GROUP_USER_GRU', 'S_BUSINESS_DATA.V_USER_USR', 'GRP_ID', 'USR_ID', '{USR_LAST_NAME} {USR_FIRST_NAME}', 'GRU_ID')
                ->unset_texteditor('GRP_DESCRIPTION')

        ;
        $crud->order_by('GRP_NAME', 'ASC');

        // Callbacks
        $crud->callback_delete(array($this, 'callbackGroupDelete'));
        $crud->callback_insert(array($this, 'callbackGroupInsert'));
        $crud->callback_update(array($this, 'callbackGroupUpdate'));

        $this->db = $this->load->database('DB_PLASTPROD', true);
        $output = $crud->render();

        $css = $crud->get_css_files();
        $js = $crud->get_js_files();

        $this->layout
                ->setTitle('Groupes')
                ->setCss($css)
                ->setJs($js)
                ->view('groups/admin', $output)
                ->display()
        ;
    }

    /* CALLBACKS */

    /**
     * Callback de suppression d'un groupe.
     * 
     * @param   int     $id
     * @return  boolean
     */
    public function callbackGroupDelete($id) {
        if ($this->acl->can('manage', false)) {
            $datas = array(
                $id
            );

            $result = callProc('DB_PLASTPROD', 'S_INTRANET', 'P_D_GROUP_00', $datas);

            if ('SUCCESS' === $result->RESULT)
                return true;
        }
        return false;
    }

    /**
     * Callback de création d'un groupe.
     * 
     * @param   array   $post
     * @return  boolean
     */
    public function callbackGroupInsert($post) {
        if ($this->acl->can('manage', false)) {
            $datas = array(
                '\'' . pg_escape_string($post['GRP_NAME']) . '\'',
                '\'' . pg_escape_string($post['GRP_DESCRIPTION']) . '\''
            );

            $result = callProc('DB_PLASTPROD', 'S_INTRANET', 'P_I_GROUP_00', $datas);

            if ('SUCCESS' === $result->RESULT) {
                // Si il y a des utilisateurs à ajouter.
                if (isset($post['USERS'])) {
                    foreach ($post['USERS'] AS $user) {
                        $datas = array(
                            $result->MESSAGE,
                            $user
                        );
                        callProc('DB_PLASTPROD', 'S_INTRANET', 'P_I_GROUP_USER_00', $datas);
                    }
                }

                return true;
            }
        }
        return false;
    }

    /**
     * Callback de mise à jour d'un groupe.
     * 
     * @param   array   $post
     * @param   int     $id
     * @return  boolean
     */
    public function callbackGroupUpdate($post, $id) {
        if ($this->acl->can('manage', false)) {
            $datas = array(
                $id,
                '\'' . pg_escape_string($post['GRP_NAME']) . '\'',
                '\'' . pg_escape_string($post['GRP_DESCRIPTION']) . '\''
            );

            $result = callProc('DB_PLASTPROD', 'S_INTRANET', 'P_U_GROUP_00', $datas);

            if ('SUCCESS' === $result->RESULT) {
                $tmp = $this->db
                        ->select('*')
                        ->from('"S_INTRANET"."P_S_GROUP_USER_BY_GROUP_00"(' . $id . ')')
                        ->get()
                        ->result()
                ;
                $usersInGroup = array();
                foreach ($tmp AS $group)
                    array_push($usersInGroup, $group->USR_ID);

                if (!isset($post['USERS']))
                    $post['USERS'] = array();

                // On retire les groupes a retirer.
                foreach ($usersInGroup AS $user) {
                    if (!in_array($user, $post['USERS'])) {
                        $datas = array(
                            $id,
                            $user
                        );
                        callProc('DB_PLASTPROD', 'S_INTRANET', 'P_D_GROUP_USER_00', $datas);
                    }
                }

                // On ajoute les groupes.
                foreach ($post['USERS'] AS $user) {
                    if (!in_array($user, $usersInGroup)) {
                        $datas = array(
                            $id,
                            $user
                        );
                        callProc('DB_PLASTPROD', 'S_INTRANET', 'P_I_GROUP_USER_00', $datas);
                    }
                }


                return true;
            }
        }
        return false;
    }

}